package com.example.oppotest.util.youku;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @Author wyk
 * @Date: 2025/2/25 22:22
 * 签名工具
 */
public class SignUtil {

    // 签名
    public static String sign(String appKey, String appSecret, String content) {
        StringBuilder keyBuilder = new StringBuilder();
        keyBuilder.append(appKey).append(content);
        return Md5Util.MD5(encrypt(keyBuilder.toString(), appSecret, "HmacSHA256"));
    }

    // HmacSHA256加密算法获取加密串
    public static String encrypt(String key, String appSecret, String cryptoType) {
        try {
            SecretKeySpec signingKey = getSecretKey(appSecret, cryptoType);
            Mac mac = Mac.getInstance(cryptoType);
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(key.getBytes());
            String hexBytes = byte2hex(rawHmac);
            return hexBytes;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static SecretKeySpec getSecretKey(String appSecret, String cryptoType) {
        try {
            byte[] keyBytes = appSecret.getBytes();
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, cryptoType);
            return secretKey;
        } catch (Exception var4) {
            return null;
        }
    }

    private static String byte2hex(final byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0xFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs;
    }



}
